package top.ijiujiu.exception;


import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import top.ijiujiu.util.ResultUtil;

/**
 * 全局异常处理
 *
 * @Author 神秘的黄瓜
 * @Version 1.0
 * @Date 2020-04-01 10:33
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常的处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResultUtil<?> exceptionHandler(Exception e) {
        e.printStackTrace();
        ResultUtil<Object> data = new ResultUtil<>();
        return data.failed("程序异常,请联系管理员~~~~~~");
    }

    /**
     * 参数校验全局异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResultUtil<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        ObjectError error = e.getBindingResult().getAllErrors().get(0);
        ResultUtil<Object> data = new ResultUtil<>();
        return data.failed(error.getDefaultMessage());
    }

    /**
     * 默认异常的处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = DefaultException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResultUtil<?> defaultExceptionHandler(DefaultException e) {
        e.printStackTrace();
        ResultUtil<Object> data = new ResultUtil<>();
        return data.failed(e.getStatus(), e.getMessage());
    }
}
